import static org.elasticsearch.node.NodeBuilder.nodeBuilder;

import java.io.IOException;
import java.util.Date;

import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.action.search.SearchType;
import org.elasticsearch.client.*;
import org.elasticsearch.common.xcontent.XContentBuilder;
import org.elasticsearch.common.xcontent.XContentFactory;
import org.elasticsearch.index.query.QueryBuilder;
import org.elasticsearch.node.Node;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.SearchHits;

import static org.elasticsearch.index.query.FilterBuilders.*;
import static org.elasticsearch.index.query.QueryBuilders.*;
import static org.elasticsearch.common.xcontent.XContentFactory.*;

public class ConnectServer {

	/**
	 * @param args
	 * @throws IOException 
	 */
	public static void main(String[] args) throws IOException {

		Node node = nodeBuilder().node();
		Client client = node.client();
		
		
		XContentBuilder doc = jsonBuilder() 
			      .startObject()       
			          .field("title", "test")  
			          .field("description", "descript what?")   
			          .field("price", 100)  
			          .field("onSale", true)  
			          .field("type", 1)  
			          .field("createDate", new Date())                            
			     .endObject();  
			client.prepareIndex("test1","test1").setSource(doc).execute().actionGet(); 
			
		    QueryBuilder qb1 = termQuery("price", "100");   

			QueryBuilder qb2 = boolQuery()
					.must(termQuery("content", "test1"))
					.must(termQuery("content", "test4"))
					.mustNot(termQuery("content", "test2"))
					.should(termQuery("content", "test3"));
			
			QueryBuilder qb3 = filteredQuery(
					termQuery("name.first", "shay"), 
					rangeFilter("age")
					.from(23)
					.to(54)
					.includeLower(true)
					.includeUpper(false)
					);
			
//			SearchResponse response = client.prepareSearch("test")   
//			.setQuery(qb1)   
//			.setFrom(0).setSize(60).setExplain(true)   
//			.execute()   
//			.actionGet();  
//			SearchHits hits = response.hits();
//			for (int i = 0; i < 60; i++) {  
//				System.out.println(hits.getAt(i).getSource().get("field"));  
//			}  
			SearchResponse response = client.prepareSearch("test")
			        .setSearchType(SearchType.DFS_QUERY_THEN_FETCH)
			        .setQuery(qb1)
			        .setFrom(0).setSize(60).setExplain(true)
			        .execute()
			        .actionGet();
			SearchHits hits = response.hits();
			for (int i = 0; i < 60; i++) {  
				System.out.println(hits.getAt(i).getSource().get("field"));  
			}  
			
			
	}

}
